//
//  ZHomeVC.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/9/10.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZHomeVC.h"
#import "ZZHomeTopView.h"
#import "ZZBottomSelectView.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "ZDrawboadView.h"
#import "ZSelectColorVc.h"
#import "ZZCameraSelectVC.h"
#import "ZZDeviceManager.h"
#import "UIColor+ZUtilities.h"
#import "UIColor+ZUtilities.h"
#import "BleManage.h"
#import "ZZAORBView.h"
#import "Timerobj.h"
#import "AppModel.h"
@interface ZHomeVC ()<BleManageDelegate>{
    
    NSInteger devNum;
    CGFloat outValue;
    UIColor *LEDAColor;
}


@property (nonatomic, strong)ZZHomeTopView *topView;

@property (nonatomic, strong)CBCentralManager *bluetoothManager;

@property (nonatomic, strong)ZZBottomSelectView *selectView;

@property (nonatomic, assign)NSInteger selectIndex;

@property (nonatomic, strong)UIButton *rightBtn;

@property (nonatomic, weak)ZZDeviceManager *devicemanager;

@property (nonatomic ,strong) ZDrawboadView *drawboadView;

@property (nonatomic ,strong) AppModel *appModel;



@end

@implementation ZHomeVC
BleManage *bleManage;//需要是全局，这个才能更好的在每个界面操作蓝牙
extern  Timerobj *timermange;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.titleView = [UIImageView zImageViewWithImage:@"img_logo"];
    self.navigationItem.rightBarButtonItem =  self.navigationItem.rightBarButtonItem = [self zNavItemWithImage:@"icon_lanmu" shouldOriginal:YES andSelector:@selector(rightNavItemClick)];
    self.selectIndex = 0;
    
    
    bleManage=[[BleManage alloc]init];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    bleManage.delegate=self;
    [super viewWillAppear:animated];
    
    
    
    if (self.selectView == nil) {
        
        [self setupSubView];

        [self.drawboadView setARect:self.appModel.homeAReact BReact:self.appModel.homeBReact];
        self.selectIndex = self.appModel.homeIndexModel;
        self.topView.sliderView.value = self.appModel.homeLightValue;
        [self.selectView setIndex:self.appModel.homeIndexModel];
    }
    [timermange myTimerStart:ZHome_timer_id timevalue:10 myFuncPtr:setLed value:0 objclass:self];
    
}

void setLed(int value,id objclass){
    [objclass mainsetLed:value];
}

-(void)mainsetLed:(int)value{//在主线程里发送
    
    if(outValue!=self.topView.sliderView.value){
        outValue=self.topView.sliderView.value;
        if (self.selectIndex == 0) {
            
             NSLog(@"亮度 = %d",value);
#pragma mark - 输出常亮亮度
        } else if (self.selectIndex == 1) {
            
            NSLog(@"渐变 = %d",value);
#pragma mark - 渐变
        }else {
            NSLog(@"频闪 = %d",value);
#pragma mark - 频闪
        }
    }
    [timermange myTimerStart:ZHome_timer_id timevalue:100 myFuncPtr:setLed value:0 objclass:self];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [timermange myTimerStart:ZHome_timer_id timevalue:1 myFuncPtr:setLed value:0 objclass:nil];//释放
    
}

- (void)hideTabBar {
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)showTabBar

{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    
    else
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = NO;
    
}


- (void)viewDidDisappear:(BOOL)animated {
    
    
    [super viewDidDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    
}

- (void)viewWillLayoutSubviews {
    
    [super viewWillLayoutSubviews];
    
    self.selectView.frame = CGRectMake(39 * Z_Scale, CGRectGetMaxY(self.rightBtn.frame) + 50 * Z_Scale, Z_SCREEN_WIDTH - 39 * Z_Scale * 2, 33);
}

#pragma mark - Func
- (void)rightNavItemClick {
    
    if (self.devicemanager) {
        
        [self.devicemanager removeFromSuperview];
        self.devicemanager = nil;
        return;
    }
    
    ZZDeviceManager *manager = [ZZDeviceManager xibInstance];
    manager.vc = self;
    
    self.devicemanager = manager;
    manager.frame = CGRectMake(Z_SCREEN_WIDTH, 64, Z_SCREEN_WIDTH, Z_SCREEN_HEIGHT - 64);
    [self.tabBarController.view addSubview:manager];
    
    [UIView animateWithDuration:0.4 animations:^{
        
        manager.x = 0;
    }];
}

- (void)leftBtnDidClick {
    
    
    ZZCameraSelectVC *vc = [[ZZCameraSelectVC alloc] init];
    vc.changeColor = ^(UIColor *color, BOOL isB) {
        
        
        if (!isB) { // A
#pragma mark - A输出的颜色
            // 输出A的颜色
            NSLog(@"A = %@",color);
            unsigned char buf[4];
            buf[0]='A';
            NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
            NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
            if (RGBArr.count > 3) {
                
                float r = [[RGBArr objectAtIndex:1] floatValue];
                float g = [[RGBArr objectAtIndex:2] floatValue];
                float b = [[RGBArr objectAtIndex:3] floatValue];
                buf[1]=r*255;buf[2]=g*255;buf[3]=b*255;
                [bleManage writeByte:[NSData dataWithBytes:buf length:4] index:0 time:10];
            }
     
        } else { //
#pragma mark - B输出的颜色
            //
            NSLog(@"B = %@",color);
            unsigned char buf[4];
            buf[0]='B';
            NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
            NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
            if (RGBArr.count >= 3) {
                
                float r = [[RGBArr objectAtIndex:1] floatValue];
                float g = [[RGBArr objectAtIndex:2] floatValue];
                float b = [[RGBArr objectAtIndex:3] floatValue];
                
                buf[1]=r*255;buf[2]=g*255;buf[3]=b*255;
                [bleManage writeByte:[NSData dataWithBytes:buf length:4] index:0 time:10];
            }
            
        }
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 输出顶部滑块值
- (void)topViewValueChange {
    

    self.appModel.homeLightValue = self.topView.sliderView.value;
    [self.appModel save];
        if(outValue!=self.topView.sliderView.value){
            outValue=self.topView.sliderView.value;
            if (self.selectIndex == 0) {
    
                
    #pragma mark - 输出常亮亮度
                NSLog(@"亮度 = %lf",outValue);
            } else if (self.selectIndex == 1) {
    
    #pragma mark - 渐变
                NSLog(@"渐变 = %lf",outValue);
            }else {
    
    #pragma mark - 频闪
                NSLog(@"频闪 = %lf",outValue);
            }
        }
    
    
    
    
}


#pragma mark - private Func

- (void)setupSubView {
    
    ZZHomeTopView *topView = [ZZHomeTopView xibInstance];
    [topView.sliderView addTarget:self action:@selector(topViewValueChange) forControlEvents:UIControlEventValueChanged];
    topView.frame = CGRectMake(0, 39 * Z_Scale + 64, Z_SCREEN_WIDTH, 40);
    self.topView = topView;
    [self.view addSubview:topView];
    
    ZDrawboadView *imageView = [ZDrawboadView xibInstance];
    self.drawboadView = imageView;
    imageView.backgroundColor = [UIColor clearColor];
    imageView.viewDidClick = ^(UIColor *color ,AorB style){
        
        switch (style) {
            case A:
            {
#pragma mark - 输出A
                //                NSData *dataA = [color changeData];
                NSLog(@"A = %@",color);
                unsigned char buf[4];
                buf[0]='A';
                NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
                NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
                float r = [[RGBArr objectAtIndex:1] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                float g = [[RGBArr objectAtIndex:2] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                float b = [[RGBArr objectAtIndex:3] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                buf[1]=r*255;buf[2]=g*255;buf[3]=b*255;
                [bleManage writeByte:[NSData dataWithBytes:buf length:4] index:0 time:10];
                //                [bleManage writeByte:data index:0 time:0];
            }
                break;
#pragma mark - 输出B
            case B:
            {
                //                NSData *dataB = [color changeData];
                NSLog(@"B = %@",color);
                unsigned char buf[4];
                buf[0]='B';
                NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
                NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
                float r = [[RGBArr objectAtIndex:1] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                float g = [[RGBArr objectAtIndex:2] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                float b = [[RGBArr objectAtIndex:3] floatValue]*[[RGBArr objectAtIndex:4] floatValue];
                buf[1]=r*255;buf[2]=g*255;buf[3]=b*255;
                [bleManage writeByte:[NSData dataWithBytes:buf length:4] index:0 time:10];
            }
                break;
            default:
                break;
        }
    };
    
    imageView.frame = CGRectMake(0, 116 * Z_Scale + 64, 287 * Z_Scale, 287 * Z_Scale);
    [self.view addSubview:imageView];
    CGPoint center = imageView.center;
    center.x = Z_SCREEN_WIDTH / 2.0;
    imageView.center = center;
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"icon_ssqs"] forState:UIControlStateNormal];
    leftBtn.frame = CGRectMake(Z_Scale * 35, CGRectGetMaxY(imageView.frame), 48 , 48);
    [leftBtn addTarget:self action:@selector(leftBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:leftBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"btn_add48px"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(addColor) forControlEvents:UIControlEventTouchDown];
    rightBtn.frame = CGRectMake(Z_SCREEN_WIDTH - Z_Scale * 35 - 48 , CGRectGetMaxY(imageView.frame), 48 , 48);
    self.rightBtn = rightBtn;
    [self.view addSubview:rightBtn];
    
    ZZBottomSelectView *selectView = [ZZBottomSelectView xibInstance];
    self.selectView = selectView;
    selectView.frame = CGRectMake(39 * Z_Scale, CGRectGetMaxY(rightBtn.frame) + 50 * Z_Scale, Z_SCREEN_WIDTH - 39 * Z_Scale * 2, 33);
    
    selectView.selectBtnClick = ^(NSInteger index) {

         self.appModel.homeIndexModel = index;
        self.selectIndex = index;
        [self.appModel save];
        switch (index) {
            case 0:
            {
                [self selectBtnOne];


            }
                break;
            case 1:
            {
                [self selectBtnTwo];

            }
                break;
            case 2:
            {
                [self selectBtnThree];

            }
                break;
                
            default:
                break;
        }
    };
    [self.view addSubview:selectView];
    
}

- (void)selectBtnOne {
    
    self.topView.leftIcon.image = [UIImage imageNamed:@"icon_line_s"];
    self.topView.rightIcon.image = [UIImage imageNamed:@"icon_line_b"];
    
}

- (void)selectBtnTwo {
    
    self.topView.leftIcon.image = [UIImage imageNamed:@"icon_pinl01"];
    self.topView.rightIcon.image = [UIImage imageNamed:@"icon_pinli02"];
}

- (void)selectBtnThree {
    
    self.topView.leftIcon.image = [UIImage imageNamed:@"icon_pinl01"];
    self.topView.rightIcon.image = [UIImage imageNamed:@"icon_pinli02"];
}

- (void)addColor {
    
    ZSelectColorVc *vc = [ZSelectColorVc zStoryboardInstance];
#pragma 收藏颜色点击输出
    vc.outPutColor = ^(UIColor *color,CGRect react) {

         [self.drawboadView selectColor:color forReact:react];
#pragma 输出A颜色
        if (!self.drawboadView.isB) { // 点击A输出颜色

            NSLog(@"%@",color);
            
        } else { // 点击B输出颜色

        }
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - CBCentralManagerDelegate
//- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
//    NSString *message = nil;
//    switch (central.state) {
//        case 1:
//            message = @"该设备不支持蓝牙功能,请检查系统设置";
//            break;
//        case 2:
//            message = @"该设备蓝牙未授权,请检查系统设置";
//            break;
//        case 3:
//            message = @"该设备蓝牙未授权,请检查系统设置";
//            break;
//        case 4:
//            message = @"该设备尚未打开蓝牙,请在设置中打开";
//        {
//
//        }
//            break;
//        case 5:
//            message = @"蓝牙已经成功开启,请稍后再试";
//            break;
//        default:
//            break;
//    }
//    if(message!=nil&&message.length!=0)
//    {
//        NSLog(@"message == %@",message);
//    }
//}

#pragma mark - 蓝牙
- (void) centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (central.state == CBCentralManagerStatePoweredOn)//已打开蓝牙
    {
        [bleManage startscan];
        NSLog(@"蓝牙正常");
    }else if (central.state == CBManagerStatePoweredOff)//蓝牙未打开
    {
        NSLog(@"蓝牙未打开");
    }else if (central.state == CBManagerStateUnauthorized)//蓝牙未授权
    {
        NSLog(@"蓝牙未授权");
    }
    
}
-(void)UpDevNum:(NSInteger)num{
    devNum=num;
    if (devNum>0&&(![bleManage getisconnect:devNum-1])) {
        [bleManage connectBle:devNum-1];
    }
    
}
-(void)BleSendOver{//蓝牙数据发送结束
}
-(void)connectSuccess:(NSInteger)index{//蓝牙连接成功
    unsigned char buf[2];
    buf[0]='a';
    buf[1]=0;
    [bleManage writeByte:[NSData dataWithBytes:buf length:2] index:index time:10];
}
-(void)Blercvdata:(NSData *)data index:(NSInteger)index{//接收到的蓝牙数据
    unsigned char *ptr=(unsigned char *)data.bytes;
    if (ptr[0]=='a') {
        if (ptr[1]==0) {
            bleManage.LEDANum=ptr[2];
            bleManage.LEDBNum=ptr[3];
        }
    }
}
#pragma mark - set & get
- (AppModel *)appModel {

    if (!_appModel) {

        _appModel = kAppModel;
    }
    return _appModel;
}

//- (NSArray *)pointColor {
//
//}


@end

